package com.elai.web.controller.baseconfig;

import com.alibaba.fastjson.JSONObject;
import com.elai.baseconfig.domain.EventMethodGlobal;
import com.elai.baseconfig.service.IEventMethodGlobalService;
import com.elai.common.core.domain.entity.SysUser;
import com.elai.common.utils.SecurityUtils;
import com.elai.common.utils.StringUtils;
import com.elai.common.annotation.Log;
import com.elai.common.core.controller.BaseController;
import com.elai.common.core.domain.AjaxResult;
import com.elai.common.core.page.TableDataInfo;
import com.elai.common.enums.BusinessType;
import com.elai.common.utils.ThirdProperties;
import com.elai.common.utils.WebUtils;
import com.elai.common.utils.poi.ExcelUtil;
import com.elai.baseconfig.domain.EventItemDO;
import com.elai.baseconfig.domain.EventMethodDO;
import com.elai.baseconfig.service.EventItemService;
import com.elai.baseconfig.service.EventMethodService;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 事件项目Controller
 *
 * @author elai
 * @date 2021-04-03
 */
@RestController
@RequestMapping("/config/item")
public class EventItemController extends BaseController
{
    @Autowired
    private EventItemService eventItemService;

    @Autowired
    private EventMethodService eventMethodService;
    //ck
    private static final String ADDCOLUMN ="addcolumn/column";
    @Autowired
    private ThirdProperties thirdProperties;

    @Autowired
    private IEventMethodGlobalService eventMethodGlobalService;

    /**
     * 查询事件项目列表
     */
    @PreAuthorize("@ss.hasPermi('config:item:list')")
    @GetMapping("/list")
    public TableDataInfo list(EventItemDO eventItem)
    {
        SysUser currentUser= SecurityUtils.getLoginUser().getUser();
        if(!currentUser.isAdmin()){
            eventItem.setLesseeId(currentUser.getLesseeId());
        }
        startPage();
        List<EventItemDO> list = eventItemService.selectEventItemList(eventItem);
        return getDataTable(list);
    }

    @GetMapping("/getItemListByType")
    public AjaxResult getItemListByType(EventItemDO eventItem)
    {
        SysUser currentUser= SecurityUtils.getLoginUser().getUser();
        if(!currentUser.isAdmin()){
            eventItem.setLesseeId(currentUser.getLesseeId());
        }
        eventItem.setStatus("Y");
        List<EventItemDO> list = eventItemService.selectEventItemList(eventItem);
        return AjaxResult.success(list);
    }

    @GetMapping("/getEventItemsList")
    public AjaxResult getEventItemsList()
    {
        SysUser currentUser= SecurityUtils.getLoginUser().getUser();
        EventItemDO eventItem=new EventItemDO();
        if(!currentUser.isAdmin()){
            eventItem.setLesseeId(currentUser.getLesseeId());
        }
        eventItem.setStatus("Y");
        List<EventItemDO> list = eventItemService.selectEventItemList(eventItem);
        Map<Long, List<EventItemDO>> eventMap = list.stream()
                .filter(val->StringUtils.isNotNull(val.getEventId()))
                .collect(Collectors.groupingBy(EventItemDO::getEventId));
        return AjaxResult.success(eventMap);
    }


    @GetMapping("/getEventItemMethods")
    public AjaxResult getEventItemMethods()
    {
        SysUser currentUser= SecurityUtils.getLoginUser().getUser();
        EventItemDO eventItem=new EventItemDO();
        if(!currentUser.isAdmin()){
            eventItem.setLesseeId(currentUser.getLesseeId());
        }
        eventItem.setStatus("Y");
        eventItem.setEventMethod("NO");
        List<EventItemDO> list = eventItemService.selectEventItemList(eventItem);
        List<EventMethodDO> methodList=eventMethodService.selectEventMethodList(new EventMethodDO());

        Map<Long, List<EventItemDO>> eventMap = list.stream()
                .filter(val->StringUtils.isNotNull(val.getEventId()))
                .collect(Collectors.groupingBy(EventItemDO::getEventId));
        Map<Long, List> resultList=new HashMap<>();
        Iterator it= eventMap.keySet().iterator();
        List<EventMethodGlobal> globalList= eventMethodGlobalService.getAllEventMethodGlobalList();
        while (it.hasNext()){
            Long listId= Long.valueOf(String.valueOf(it.next()));
            List<EventItemDO> eventList=eventMap.get(listId);

            List mapList=new ArrayList();
            globalList.stream().forEach(global->{
                Map sumItem=new HashMap();
                sumItem.put("value",global.getMethodStr());
                sumItem.put("label",global.getMethodName());
                sumItem.put("valueType",global.getExtra1());
                mapList.add(sumItem);
            });
            for(EventItemDO item : eventList){
                if(StringUtils.isNotEmpty(item.getEventMethod())){
                    String str=item.getEventMethod();
                    Map itemMap=new HashMap();
                    itemMap.put("value",item.getEventItemCode());
                    itemMap.put("label",item.getEventItemName());
                    itemMap.put("valueType",item.getValueType());
                    List<Map<String,String>> childList=new ArrayList<Map<String,String>>();
                    String ids[]=str.split(",");
                    for(String id:ids){
                        if("NaN".equals(id))continue;
                        EventMethodDO m=methodList.stream().filter(p -> p.getId() == Long.parseLong(id)).findFirst().get();
                        if(m!=null){
                            Map childIitemMap=new HashMap();
                            childIitemMap.put("value",m.getMethodStr());
                            childIitemMap.put("label",m.getMethodName());
                            childList.add(childIitemMap);
                        }
                    }
                    itemMap.put("children",childList);
                    mapList.add(itemMap);
                }
            }
            resultList.put(listId,mapList);
        }
        return AjaxResult.success(resultList);
    }



    @GetMapping("/getItemGroupsByType")
    public AjaxResult getItemGroupsByType(EventItemDO eventItem)
    {
        SysUser currentUser= SecurityUtils.getLoginUser().getUser();
        if(!currentUser.isAdmin()){
            eventItem.setLesseeId(currentUser.getLesseeId());
        }
        eventItem.setStatus("Y");
        List list = eventItemService.selectEventItemsGroup(eventItem);
        return AjaxResult.success(list);
    }


    /**
     * 导出事件项目列表
     */
    @PreAuthorize("@ss.hasPermi('config:item:export')")
    @Log(title = "事件项目", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(EventItemDO eventItem)
    {
        SysUser currentUser= SecurityUtils.getLoginUser().getUser();
        if(!currentUser.isAdmin()){
            eventItem.setLesseeId(currentUser.getLesseeId());
        }
        List<EventItemDO> list = eventItemService.selectEventItemList(eventItem);
        ExcelUtil<EventItemDO> util = new ExcelUtil<EventItemDO>(EventItemDO.class);
        return util.exportExcel(list, "item");
    }

    /**
     * 获取事件项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('config:item:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(eventItemService.selectEventItemById(id));
    }

    /**
     * 新增事件项目
     */
    @PreAuthorize("@ss.hasPermi('config:item:add')")
    @Log(title = "事件项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EventItemDO eventItem)
    {
        Map<String, Object> paramMap =new HashedMap();
        paramMap.put("columnName",eventItem.getEventItemCode());
        paramMap.put("columnComment",eventItem.getEventItemName());
        JSONObject obj= WebUtils.postCkObj(thirdProperties.getCkUrl(),ADDCOLUMN,paramMap);
        System.out.println("增加字段:"+obj);
        return toAjax(eventItemService.insertEventItem(eventItem));
    }

    /**
     * 修改事件项目
     */
    @PreAuthorize("@ss.hasPermi('config:item:edit')")
    @Log(title = "事件项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EventItemDO eventItem)
    {
        return toAjax(eventItemService.updateEventItem(eventItem));
    }

    /**
     * 删除事件项目
     */
    @PreAuthorize("@ss.hasPermi('config:item:remove')")
    @Log(title = "事件项目", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(eventItemService.deleteEventItemByIds(ids));
    }
}
